﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using eventr.ImageViewDataService;
using System.Diagnostics;

namespace eventr.View
{
    public partial class ImageOverlay : UserControl
    {
        ImageMetaData metaData;

        bool visible = false;
        bool stats = false;

        public ImageOverlay()
        {
            InitializeComponent();
            this.Loaded += (s, e) =>
            {
                KeyValuePair<int, object> item = (KeyValuePair<int, object>)DataContext;
                metaData = item.Value as ImageMetaData;

                if (metaData != null)
                {
                    metaData.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(d_PropertyChanged);
                }
            };

            Media.MediaEnded += new RoutedEventHandler(Media_MediaEnded);                  
        }

        void d_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            visible = metaData.Viewed;
            stats = metaData.ShowStats;            

            updateStates(true);
            configureMedia();
        }

        void updateStates(bool trans)
        {
            
                if (visible)
                {
                    VisualStateManager.GoToState(this, "Visible", trans);
                }
                else
                {
                    VisualStateManager.GoToState(this, "Invisible", trans);
                }           
                
                if (stats)
                {
                    VisualStateManager.GoToState(this, "StatsOn", trans);
                }
                else
                {
                    VisualStateManager.GoToState(this, "StatsOff", trans);
                }
            
        }

        void configureMedia()
        {
            if (metaData.Video != string.Empty && visible)
            {
                metaData.PauseSlideshow();
                Media.Source = new Uri(metaData.Video, UriKind.RelativeOrAbsolute);
                Media.Play();
            }
            else
            {
                visible = false;
                Media.Stop();
                Media.Source = null;
                updateStates(true);
            }
        }

        void Media_MediaEnded(object sender, RoutedEventArgs e)
        {
            visible = false;
            updateStates(true);
            metaData.ResumeSlideshow();
        }
    }
}
